import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message {
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    // 构建 ObjectMapper
    private ObjectMapper objectMapper = new ObjectMapper();

    // 向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 把 body 的内容读取出来，解析成一个 Massage 对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        save(message);
        // 设置状态码，不设置默认也是 200
        resp.setStatus(200);
    }

    // 从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 显示的告诉浏览器，数据格式是 json 格式，字符集是 utf-8
        resp.setContentType("application/json; charset=utf8");
        List<Message> messageList = load();
        // 第一个参数表示写到哪里，第二个参数表示写的内容是什么
        objectMapper.writeValue(resp.getWriter(), messageList);
    }

    // 提供一对方法来保存数据
    // 往数据库中存一条数据
    private void save(Message messageWall) {
        // JDBC 操作
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1.建立连接
            connection = DBUtil.getConnection();
            // 2.构造 sql 语句
            String sql = "insert into messagewall values(?, ?, ?)";
            statement = (PreparedStatement)connection.prepareStatement(sql);
            // 将上面的三个 ? 占位符替换为 from to message
            statement.setString(1, messageWall.from);
            statement.setString(2, messageWall.to);
            statement.setString(3, messageWall.message);
            // 3.执行 sql
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4.关闭连接
            DBUtil2.close(connection, statement, null);
        }
    }

    // 从数据库中拿出所有数据
    private List<Message> load() {

        List<Message> messageList = new ArrayList<>();

        Connection connection = null;
        ResultSet resultSet = null;
        PreparedStatement statement = null;
        try {
            // 1.和数据库建立连接
            connection = DBUtil.getConnection();
            // 2.构造 sql 语句
            String sql = "select * from messagewall";
            statement = (PreparedStatement)connection.prepareStatement(sql);
            // 3.执行 sql
            resultSet = statement.executeQuery();
            // 4.遍历结果集合
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                // 存到 messageList 中
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5.断开连接
            DBUtil2.close(connection, statement, resultSet);
        }
        return messageList;
    }
}
